package com.itheima.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.R;
import com.itheima.dao.DishDao;
import com.itheima.dao.DishFlavorDao;
import com.itheima.domain.Dish;
import com.itheima.domain.DishFlavor;
import com.itheima.dto.DishDto;
import com.itheima.service.DishFlovarService;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {
    @Autowired
    private DishDao dishDao;

    @Autowired
    private DishFlavorDao dishFlavorDao;

    @Autowired
    private DishFlovarService dishFlovarService;

    /**
     * 保存
     *
     * @param dishDto
     * @return
     */
    @Override
    public R saveWithFlovar(DishDto dishDto) {
        //先将数据保存到dish表中
        int dish = dishDao.insert(dishDto);
        //获取 dish 的id
        Long dishId = dishDto.getId();

        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
            dishFlavorDao.insert(flavor);
        }
        return R.success("添加成功");


    }

    /**
     * 查询菜单表和口味表
     * @param id
     * @return
     */
    @Override
    public DishDto getWithFlavor(Long id) {
        //查询菜单表
        Dish dish = this.getById(id);
        DishDto dishDto1 = new DishDto();
        BeanUtils.copyProperties(dish, dishDto1);

        //查询口味表
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, id);
        List<DishFlavor> dishFlavors = dishFlavorDao.selectList(lqw);
        dishDto1.setFlavors(dishFlavors);
        return dishDto1;
    }

    /**
     *   修改信息
     * @param dishDto
     * @return
     */
    @Override
    public R updateWithFlavor(DishDto dishDto) {
        //先修改菜单表
        dishDao.updateById(dishDto);
        //修改口味表
        // 1.先删除数据
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorDao.delete(lqw);

        //2.再添加数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        for(DishFlavor dishFlavor : flavors){
            dishFlavor.setDishId(dishDto.getId());
        }
        dishFlovarService.saveBatch(flavors);
        return R.success("数据修改成功");
    }
}
